package com.yaorange.jk.web.baseinfo;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;
import com.yaorange.jk.entity.Factory;
import com.yaorange.jk.entity.Product;
import com.yaorange.jk.service.FactoryService;
import com.yaorange.jk.service.ProductService;
import com.yaorange.jk.utils.Pagination;
import com.yaorange.jk.web.BaseAction;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.util.List;


@Controller("productAction")
@Scope("prototype")
public class ProductAction extends BaseAction implements ModelDriven<Product>  {

    @Autowired
    private ProductService productService;

    @Autowired
    private FactoryService factoryService;
    private Pagination page=new Pagination();

    private List<Product> productList;

    private Product model= new Product();

    private List<Factory> fac;
    public String list(){

        Pagination pagination =  productService.findPage(page);
        pagination.setUrl("productAction_list");
        ActionContext.getContext().getValueStack().push(pagination);
        return "list";
    }

    public String tocreate(){
        fac = factoryService.findAll();
        //push(fac);
        //ServletActionContext.getRequest().setAttribute("fac",fac);
        return "tocreate";
    }

    public String insert(){
        productService.save(model);
        return list();
    }

    public String toupdate(){
    Product product = productService.findById(model.getId());
    super.push(product);

    productList = productService.findAll();
    productList.remove(product);
    return "toupdate";
    }

    public String update(){
    productService.update(model);
    return list();
    }

    /**
    * @return
    */
    public String delete(){
    String[] ids = model.getId().split(", ");
    for (String id:ids) {
    productService.deleteById(model.getId());
    }

    return list();
    }

    public String toview()
    {
    Product product = productService.findById(model.getId());
    push(product);
    return "toview";
    }
    public void setPage(Pagination page) {
    this.page = page;
    }

    public List<Product> getProductList() {
    return productList;
    }

    public List<Factory> getFac() {
        return fac;
    }

    public void setFac(List<Factory> fac) {
        this.fac = fac;
    }

    @Override
    public Product getModel() {
    return model;
    }
}
